package edu.tces482.plms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import edu.tces482.plms.zigbee.ZBReceivePacket;

public class ParkingLot 
{
	Connection con = null;
	PreparedStatement pst = null; 

	private static final String url = "jdbc:mysql://localhost:3306/plms";
	private static final String user = "plms_user";
	private static final String password = "p1m5us3r";

	public int updateStatus(ZBReceivePacket packet) 
	{ 
		try 
		{
			
			
			con = DriverManager.getConnection(url, user, password);
			
			pst = con.prepareStatement("UPDATE parking_lot SET status=?, updated=? WHERE node_id=? AND node_space=?");
			pst.setInt(1, packet.getRfData()[0] & 0x01);
			pst.setLong(2, System.currentTimeMillis());
			pst.setLong(3, packet.get64BitSourceAddress().longValue()); 
			pst.setInt(4, 0);
			pst.executeUpdate();

			pst = con.prepareStatement("UPDATE parking_lot SET status=?, updated=? WHERE node_id=? AND node_space=?");
			pst.setInt(1, (packet.getRfData()[0] & 0x02) >> 1);
			pst.setLong(2, System.currentTimeMillis());
			pst.setLong(3, packet.get64BitSourceAddress().longValue()); 
			pst.setInt(4, 1);
			pst.executeUpdate();
		} 
		catch (SQLException ex) 
		{
			if (con != null) 
			{
				try 
				{
					con.rollback();
				} 
				catch (SQLException ex1) 
				{ 
					Logger lgr = Logger.getLogger(ParkingLot.class.getName());
					lgr.log(Level.SEVERE, ex.getMessage(), ex);
				}
				Logger lgr = Logger.getLogger(ParkingLot.class.getName());
				lgr.log(Level.SEVERE, ex.getMessage(), ex);
			}
		} 
		finally 
		{
			try 
			{
				if (pst != null) 
				{
					pst.close();
				}
				if (con != null) 
				{
					con.close();
				}
			} 
			catch (SQLException ex) 
			{
				Logger lgr = Logger.getLogger(ParkingLot.class.getName());
				lgr.log(Level.WARNING, ex.getMessage(), ex);
			}
		}
		return 0; //need to make a meaningful return 
	}
}


